using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace my_newconsole;

public static class Extensions
{
    /// <summary>
    /// 转化为JObject数据
    /// </summary>
    /// <param name="xml"></param>
    /// <returns></returns>
    public static JObject ToJObject(this string xml)
    {
        xml = Regex.Replace(xml, @"<\?xml.+\?>", "").Trim();
        var doc = new XmlDocument();
        doc.LoadXml(xml);
        return JObject.Parse(JsonConvert.SerializeXmlNode(doc));
    }

    /// <summary>
    /// 转化为xml字符串
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <param name="isDeleteHeader"></param>
    /// <returns></returns>
    public static string ToXml<T>(this T obj, bool isDeleteHeader = false)
    {
        var defaultNamespace = new XmlSerializerNamespaces();
        defaultNamespace.Add("", "");
        using (var sw = new StringWriterWithEncoding(Encoding.UTF8))
        {
            var serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(sw, obj, defaultNamespace);
            var xml = sw.ToString();
            if (isDeleteHeader) // 去掉xml的头部
            {
                xml = Regex.Replace(xml, @"<\?xml.+\?>", "").Trim();
            }
            return xml;
        }
    }
}
